<template>
  <div>

    <div class="d-flex align-center justify-space-between mb-3">
      <div class="text-h6 font-weight-bold brand-logo">Permission Management</div>
      <div class="d-flex align-center">
        <v-text-field
          v-model.trim="queryInput"
          class="mr-2"
          style="width: 280px;"
          outlined
          dense
          clearable
          hide-details
          label="Search (e.g. key:user.read code:P01)"
          append-icon="mdi-magnify"
          @keyup.enter="onSearchFromInput"
          @click:append="onSearchFromInput"
          @click:clear="onResetInput"
        />
        <v-btn class="mr-2" outlined>Export</v-btn>
        <v-btn color="primary" dark @click="openAddDialog">+ Add Permission</v-btn>
      </div>
    </div>

    <v-data-table
      :headers="headers"
      :items="perms"
      :items-per-page="pageSize"
      :page.sync="pageNum"
      :server-items-length="total"
      :loading="loading"
      class="elevation-1"
      dense
      @update:page="onPageChange"
      @update:items-per-page="onPageSizeChange"
    >
      <template v-slot:item.actions>
        <v-btn x-small outlined color="primary" class="mr-1" @click="openEditDialog(item)">Edit</v-btn>
        <v-btn x-small outlined color="error" @click="confirmDelete(item)">Delete</v-btn>
      </template>
    </v-data-table>

    <!-- Add/Edit Permission Dialog -->
    <v-dialog v-model="dialog" max-width="520px">
      <v-card>
        <v-card-title class="font-weight-bold">{{ isEdit ? 'Edit Permission' : 'Add Permission' }}</v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          <v-form ref="form" v-model="formValid">
            <v-text-field v-model="formModel.permCode" label="Code" outlined dense :rules="[rules.required]" />
            <v-text-field v-model="formModel.permKey" label="Key" outlined dense :rules="[rules.required]" />
            <v-text-field v-model="formModel.description" label="Description" outlined dense :rules="[rules.required]" />
          </v-form>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions class="justify-end">
          <v-btn text @click="closeDialog">Cancel</v-btn>
          <v-btn color="primary" dark @click="submitPerm">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
export default {
  name: 'PermissionPage',
  data() {
    return {
      headers: [
        { text: 'ID', value: 'id' },
        { text: 'CODE', value: 'permCode' },
        { text: 'KEY', value: 'permKey' },
        { text: 'DESCRIPTION', value: 'description' },
        { text: 'ACTIONS', value: 'actions', sortable: false }
      ],
      perms: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      loading: false,
      queryInput: '',
      query: { permKey: '', permCode: '', description: '' },
      dialog: false,
      isEdit: false,
      formValid: false,
      formModel: { id: '', permCode: '', permKey: '', description: '' },
      rules: { required: v => !!(v && String(v).trim()) || 'Required' }
    }
  },
  created() {
    this.fetchPerms()
  },
  methods: {
    async fetchPerms() {
      this.loading = true
      try {
        const q = { ...this.query }
        Object.keys(q).forEach(k => { if (q[k] === '' || q[k] === null || typeof q[k] === 'undefined') delete q[k] })
        const res = await this.$api.permission.getPermissions({ pageNum: this.pageNum, pageSize: this.pageSize, ...q })
        const payload = res && (res.data || res)
        this.perms = payload.list || payload.items || []
        this.total = Number(payload.total || payload.totalCount || 0)
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to fetch permissions', e)
      } finally {
        this.loading = false
      }
    },
    onSearch() { this.pageNum = 1; this.fetchPerms() },
    onReset() { this.query = { permKey: '', permCode: '', description: '' }; this.pageNum = 1; this.fetchPerms() },
    onSearchFromInput() {
      const params = this.parseQueryInput(this.queryInput)
      this.query = { permKey: '', permCode: '', description: '', ...params }
      this.pageNum = 1
      this.fetchPerms()
    },
    onResetInput() {
      this.queryInput = ''
      this.onReset()
    },
    parseQueryInput(input) {
      const params = {}
      if (!input || !input.trim()) return params
      const tokens = input.trim().split(/\s+/)
      tokens.forEach(t => {
        const idx = t.indexOf(':')
        if (idx > 0) {
          const key = t.slice(0, idx).toLowerCase()
          const val = t.slice(idx + 1)
          if (['key','permkey'].includes(key)) params.permKey = val
          else if (['code','permcode'].includes(key)) params.permCode = val
          else if (['desc','description'].includes(key)) params.description = val
        } else {
          // Bare keyword used for both permKey and permCode
          if (!params.permKey) params.permKey = t
          if (!params.permCode) params.permCode = t
        }
      })
      return params
    },
    async confirmDelete(item) {
      if (!item || !item.id) return
      const ok = window.confirm(`Delete permission "${item.permKey}"?`)
      if (!ok) return
      try {
        await this.$api.permission.deletePermission(item.id)
        this.fetchPerms()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to delete permission', e)
      }
    },
    onPageChange(p) { this.pageNum = p; this.fetchPerms() },
    onPageSizeChange(size) { this.pageSize = size; this.pageNum = 1; this.fetchPerms() },
    openAddDialog() {
      this.isEdit = false
      this.formModel = { id: '', permCode: '', permKey: '', description: '' }
      this.dialog = true
    },
    openEditDialog(item) {
      this.isEdit = true
      this.formModel = { ...item }
      this.dialog = true
    },
    closeDialog() {
      this.dialog = false
      this.$nextTick(() => { if (this.$refs.form) this.$refs.form.resetValidation() })
    },
    async submitPerm() {
      if (!this.$refs.form || !this.$refs.form.validate()) return
      try {
        if (this.isEdit) {
          await this.$api.permission.updatePermission(this.formModel.id, {
            permCode: this.formModel.permCode,
            permKey: this.formModel.permKey,
            description: this.formModel.description
          })
        } else {
          await this.$api.permission.createPermission({
            permCode: this.formModel.permCode,
            permKey: this.formModel.permKey,
            description: this.formModel.description
          })
        }
        this.closeDialog()
        this.fetchPerms()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to submit permission', e)
      }
    }
  }
}
</script>

<style scoped>
</style>


